package service

import (
	"fmt"
	domain2 "ruoyi-go/internal/web/system/domain"
	"strings"
)

// SelectMenuPermsByRoleId 查询角色菜单
func SelectMenuPermsByRoleId(roleId int) []string {
	list := domain2.SysMenuModel().SelectMenuPermsByRoleId(roleId)
	result := make([]string, 0)
	for _, s := range list {
		if len(s) > 0 {
			s1 := strings.Trim(s, " ")
			result = append(result, strings.Split(s1, ",")...)
		}
	}
	return result
}

// SelectMenuPermsByUserId 查询个人菜单
func SelectMenuPermsByUserId(userId int) []string {
	return domain2.SysMenuModel().SelectMenuPermsByUserId(userId)
}

// SelectMenuTreeByUserId 为用户查询菜单树
func SelectMenuTreeByUserId(userId int) []*domain2.SysMenu {
	var list []*domain2.SysMenu
	if domain2.IsAdminUser(userId) {
		list = domain2.SysMenuModel().SelectMenuTreeAll()
	} else {
		list = domain2.SysMenuModel().SelectMenuTreeByUserId(userId)
	}
	return MenuListToTree(list)
}

// MenuListToTree list转为树
func MenuListToTree(menuList []*domain2.SysMenu) []*domain2.SysMenu {
	var menuTree []*domain2.SysMenu
	menuMap := make(map[int]*domain2.SysMenu)
	// Create a map of menus for quick lookup by ID
	for _, menu := range menuList {
		menuMap[menu.MenuId] = menu
	}
	// Build the tree structure
	for _, menu := range menuList {
		if menu.ParentId == 0 { // Top-level menus have ParentId 0
			menuTree = append(menuTree, menu)
		} else {
			parentMenu, ok := menuMap[menu.ParentId]
			if ok {
				parentMenu.Children = append(parentMenu.Children, menu)
			} else {
				// Handle orphaned menus (menus with non-existent parents) - if necessary
				fmt.Println("Orphaned menu:", menu.MenuName)
			}
		}
	}

	return menuTree
}
